package com.hefeng.wx.common;

import com.hefeng.common.redis.service.RedisService;
import com.hefeng.wx.domain.WxUser;
import com.hefeng.wx.domain.entity.UserInfo;
import com.hefeng.wx.mapper.WxDeviceUserMapper;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Component
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class SimpleSchedule {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    WxDeviceUserMapper wxDeviceUserMapper;
    @Autowired
    RedisService redisService;
    /*@Scheduled(cron = "0 10 0/1 * * ?")   //定时器定义，设置执行时间
    private void process() {
        Map paramMap=StartLoadingParameter.paramMap;
        Map<String,Object> map=new HashMap<>();
        map.put("autoLogin",true);
        map.put("encrypt","aGVmZW5nJWdhc19hdXRoX29yaXphdGlvbiVlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZQ==");
        HttpEntity<?> request = new HttpEntity<>(map);
        JSONObject data=restTemplate.postForObject(StartLoadingParameter.getAccessTokenUrl+StartLoadingParameter.loginData,request,JSONObject.class);
        try {
            paramMap.put("userId",data.getJSONObject("obj").getString("userId"));
            paramMap.put("tokenHead",data.getJSONObject("obj").getString("tokenHead"));
            paramMap.put("token",data.getJSONObject("obj").getString("token"));
        }catch (Exception e){
            e.printStackTrace();
        }
    }*/
    /**
     * 方法说明: 定时获取用户与设备的绑定信息
     * @param
     * @return null
     * @Author: huzh
     * @Date: 2022/11/1
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public  void setUserDindingDevice(){
        redisService.deleteObject("UserBindingList");
        List<Map<String,String>>list=wxDeviceUserMapper.getUserBindingDevice();
        List<UserInfo > userInfos=new ArrayList<>();
        list.forEach(i->{
            String[] ids=i.get("userIds").split(",");
            String[] phones=i.get("phones").split(",");
            for (int v=0;v<ids.length;v++){
                UserInfo user=new UserInfo();
                user.setDeviceCode(i.get("deviceCode"));
                user.setUserId(ids[v]);
                user.setPhone(phones[v]);
                userInfos.add(user);
            }
        });
        //数据添加到缓存里
        redisService.setCacheList("UserBindingList",userInfos);
    }

}

